package org.shagin.jfin.data.model;

import java.util.List;

public class OperationCategoryUserObjectCreator<C, L> {
    public interface IUserObjectHandler<C, L> {
        L newLeafUserObject(OperationRule rule);

        void addLeafUserObject(C parent, L obj);

        C newCategoryUserObject(OperationCategory cat);

        void addCategoryUserObject(C parent, C obj);

    }

    public void createOperationCategoryUserObjects(C parent,
            List<OperationRule> rules, IUserObjectHandler<C, L> handler) {
        for (OperationCategory root : OperationRule.getRoots(rules))
            handler.addCategoryUserObject(parent,
                    addOperationCategoryUserObjects(null, root, handler));

    }

    public C addOperationCategoryUserObjects(C parent, OperationCategory cat,
            IUserObjectHandler<C, L> handler) {
        C catUserObject = handler.newCategoryUserObject(cat);

        if (parent != null) {
            handler.addCategoryUserObject(parent, catUserObject);
        }

        if (cat instanceof OperationCategoryLeaf) {
            OperationCategoryLeaf c = (OperationCategoryLeaf) cat;
            for (OperationRule rule : c.getRules()) {
                handler.addLeafUserObject(catUserObject,
                        handler.newLeafUserObject(rule));
            }
        } else
            for (OperationCategory child : cat.getChilds())
                addOperationCategoryUserObjects(catUserObject, child, handler);

        return catUserObject;
    }
}
